package net.documentshare.question.remark;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.documentshare.i.ICommonBeanAware;
import net.documentshare.question.EQuestionStatus;
import net.documentshare.question.QuestionBean;
import net.documentshare.question.QuestionUtils;
import net.documentshare.utils.ItSiteUtil;
import net.simpleframework.ado.IDataObjectValue;
import net.simpleframework.ado.db.ITableEntityManager;
import net.simpleframework.ado.db.event.TableEntityAdapter;
import net.simpleframework.content.ContentUtils;
import net.simpleframework.core.id.LongID;
import net.simpleframework.organization.OrgUtils;
import net.simpleframework.organization.account.IAccount;
import net.simpleframework.util.HTTPUtils;
import net.simpleframework.util.LocaleI18n;
import net.simpleframework.web.page.IForward;
import net.simpleframework.web.page.component.ComponentParameter;
import net.simpleframework.web.page.component.HandleException;
import net.simpleframework.web.page.component.base.ajaxrequest.AbstractAjaxRequestHandle;
import net.simpleframework.web.page.component.ui.validatecode.DefaultValidateCodeHandle;

public class QuestionRemarkAction extends AbstractAjaxRequestHandle {
	/**
	 * 设为最近答案 
	 * @param compParameter
	 * @return
	 */
	public IForward setGoodAnswer(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {

			@Override
			public void doAction(Map<String, Object> json) throws Exception {
				final QuestionBean questionBean = QuestionUtils.getQuestionBean(compParameter);
				if (questionBean != null) {
					final QuestionRemarkItem questionRemarkItem = QuestionRemarkUtils.applicationModule.getBean(QuestionRemarkItem.class,
							compParameter.getRequestParameter("itemId"));
					if (questionRemarkItem != null) {
						questionRemarkItem.setGoodAnswer(true);
						QuestionRemarkUtils.applicationModule.doUpdate(new Object[] { "goodAnswer" }, questionRemarkItem, new TableEntityAdapter() {
							@Override
							public void afterUpdate(ITableEntityManager manager, Object[] objects) {
								questionBean.setStatus(EQuestionStatus.find);
								QuestionUtils.applicationModule.doUpdate(new Object[] { "status" }, questionBean, new TableEntityAdapter() {
									@Override
									public void afterUpdate(ITableEntityManager manager, Object[] objects) {
										//交换积分
										final IAccount account = ItSiteUtil.getAccountById(ItSiteUtil.getLoginUser(compParameter).getId());
										if (account != null) {
											final int reward = Math.min(account.getPoints(), questionBean.getReward());
											account.setPoints(account.getPoints() - reward);
											OrgUtils.am().getEntityManager()
													.updateTransaction(new Object[] { "points" }, account, new TableEntityAdapter() {
														public void afterUpdate(ITableEntityManager manager, Object[] objects) {
															final IAccount toaccount = ItSiteUtil.getAccountById(questionRemarkItem.getUserId());
															toaccount.setPoints(toaccount.getPoints() + reward);
															OrgUtils.am().update(new String[] { "points" }, toaccount);
														};
													});
										}
									}
								});
							}
						});
					}
				}
			}
		});
	}

	public IForward saveRemark(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				if (!DefaultValidateCodeHandle.isValidateCode(compParameter.request, "textRemarkHtmlEditorValidateCode")) {
					json.put("validateCode", DefaultValidateCodeHandle.getErrorString());
				} else {
					QuestionRemarkItem questionRemarkItem = QuestionRemarkUtils.applicationModule.getBean(QuestionRemarkItem.class,
							compParameter.getRequestParameter("itemId"));
					if (questionRemarkItem == null) {
						questionRemarkItem = new QuestionRemarkItem();
						questionRemarkItem.setParentId(new LongID(compParameter.getRequestParameter("parentId")));
						questionRemarkItem.setCreateDate(new Date());
						questionRemarkItem.setDocumentId(new LongID(compParameter.getRequestParameter("questionId")));
						questionRemarkItem.setUserId(ItSiteUtil.getLoginUser(compParameter).getId());
					}
					questionRemarkItem.setLastUserId(ItSiteUtil.getLoginUser(compParameter).getId());
					questionRemarkItem.setLastUpdate(new Date());
					questionRemarkItem.setIp(HTTPUtils.getRemoteAddr(compParameter.request));
					questionRemarkItem.setContent(compParameter.getRequestParameter("textareaRemarkHtmlEditor"));
					QuestionRemarkUtils.applicationModule.doUpdate(questionRemarkItem);
				}
			}
		});
	}

	public IForward save2Remark(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			QuestionRemarkItem questionRemarkItem;

			@Override
			public void doAction(final Map<String, Object> json) {
				if (!DefaultValidateCodeHandle.isValidateCode(compParameter.request, "textRemarkEditorValidateCode")) {
					json.put("validateCode", DefaultValidateCodeHandle.getErrorString());
				} else {
					questionRemarkItem = QuestionRemarkUtils.applicationModule.getBean(QuestionRemarkItem.class,
							compParameter.getRequestParameter("itemId"));
					if (questionRemarkItem == null) {
						questionRemarkItem = new QuestionRemarkItem();
						questionRemarkItem.setDocumentId(new LongID(compParameter.getRequestParameter("questionId")));
						questionRemarkItem.setUserId(ItSiteUtil.getLoginUser(compParameter).getId());
					}
					questionRemarkItem.setLastUserId(ItSiteUtil.getLoginUser(compParameter).getId());
					questionRemarkItem.setContent(ContentUtils.doTextContent(compParameter.getRequestParameter("textareaRemarkEditor")));
					questionRemarkItem.setCreateDate(new Date());
					questionRemarkItem.setIp(HTTPUtils.getRemoteAddr(compParameter.request));
					QuestionRemarkUtils.applicationModule.doUpdate(questionRemarkItem, new TableEntityAdapter() {
						@Override
						public void afterInsert(ITableEntityManager manager, Object[] objects) {
							QuestionBean questionBean = QuestionUtils.applicationModule.getBean(QuestionBean.class,questionRemarkItem.getDocumentId());
							if (questionBean != null) {
								final ITableEntityManager tMgr = QuestionUtils.applicationModule.getDataObjectManager();
								questionBean.setRemarks(questionBean.getRemarks() + 1);
								tMgr.update(new Object[] { "remarks" }, questionBean);
								ICommonBeanAware.Utils.updateRemarks(compParameter, QuestionUtils.applicationModule.getDataObjectManager(),
										QuestionBean.class, questionRemarkItem.getDocumentId());
								if (questionBean.isEmail())
									//发送邮件
									QuestionRemarkUtils.applicationModule.doRemarkSent(compParameter, questionRemarkItem);
							}
						}
					});
				}
			}
		});
	}

	public IForward doSupport(final ComponentParameter compParameter) {
		return doSupportOpposition(compParameter, true);
	}

	public IForward doOpposition(final ComponentParameter compParameter) {
		return doSupportOpposition(compParameter, false);
	}

	private IForward doSupportOpposition(final ComponentParameter compParameter, final boolean support) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final String itemId = compParameter.getRequestParameter("itemId");
				final String sessionKey = "remark_support_opposition_" + itemId;
				final HttpSession httpSession = compParameter.getSession();
				if (Boolean.TRUE.equals(compParameter.getSessionAttribute(sessionKey))) {
					throw HandleException.wrapException(LocaleI18n.getMessage("RemarkAction.0"));
				}
				final QuestionRemarkItem remark = QuestionRemarkUtils.applicationModule.doSupportOpposition(compParameter, itemId, support);
				if (remark != null) {
					httpSession.setAttribute(sessionKey, Boolean.TRUE);
					json.put("k", "remark_" + (support ? "support" : "opposition") + "_" + remark.getId());
					json.put("v", "(" + (support ? remark.getSupport() : remark.getOpposition()) + ")");
				}
			}
		});
	}

	public IForward doDelete(final ComponentParameter compParameter) {
		return jsonForward(compParameter, new JsonCallback() {
			@Override
			public void doAction(final Map<String, Object> json) {
				final QuestionRemarkItem questionRemarkItem = QuestionRemarkUtils.applicationModule.getBean(QuestionRemarkItem.class,
						compParameter.getRequestParameter("itemId"));
				if (questionRemarkItem != null) {
					QuestionRemarkUtils.applicationModule.doDelete(questionRemarkItem, new TableEntityAdapter() {
						@Override
						public void afterDelete(ITableEntityManager manager, IDataObjectValue dataObjectValue) {
							QuestionBean questionBean = QuestionUtils.applicationModule.getBean(QuestionBean.class,questionRemarkItem.getDocumentId());
							if (questionBean != null) {
								final ITableEntityManager tMgr = QuestionUtils.applicationModule.getDataObjectManager();
								questionBean.setRemarks(questionBean.getRemarks() - 1);
								tMgr.update(new Object[] { "remarks" }, questionBean);
							}
						}
					});
				}
			}
		});
	}

	@Override
	public Map<String, Object> getFormParameters(ComponentParameter compParameter) {
		final Map<String, Object> parameters = super.getFormParameters(compParameter);
		putParameter(compParameter, parameters, "questionId");
		return parameters;
	}

	@Override
	public Object getBeanProperty(final ComponentParameter compParameter, final String beanProperty) {
		return super.getBeanProperty(compParameter, beanProperty);
	}
}
